package com.itheima.servlet;

import com.itheima.domain.User;
import com.itheima.service.UserService;
import com.itheima.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@WebServlet("/user")
public class UserServlet extends BaseServlet{

    // 查询所有
    public void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        UserService service = new UserServiceImpl();
        List<User> users = service.findAll();

        request.setAttribute("users", users);

        request.getRequestDispatcher("/User_List.jsp").forward(request, response);
    }

    // 添加用户
    public void add(HttpServletRequest request, HttpServletResponse response) {
        try {

            Map<String, String[]> map = request.getParameterMap();

            User user = new User();
            BeanUtils.populate(user, map);

            UserService service = new UserServiceImpl();
            service.addUser(user);

            response.sendRedirect(request.getContextPath() + "/user?method=findAll");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void update(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, String[]> map = request.getParameterMap();

            User user = new User();
            BeanUtils.populate(user, map);

            UserService service = new UserServiceImpl();
            service.updateUser(user);

            response.sendRedirect(request.getContextPath() + "/user?method=findAll");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void findById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String id = request.getParameter("id");

        UserService service = new UserServiceImpl();
        User user = service.findById(id);

        request.setAttribute("user", user);

        request.getRequestDispatcher("/User_Update.jsp").forward(request, response);
    }

    public void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String id = request.getParameter("id");

        UserService service = new UserServiceImpl();
        service.deleteById(id);

        response.sendRedirect(request.getContextPath() + "/user?method=findAll");
    }
}
